package cn.sumpu.app.guoguojie.biz.impl.security;

//import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.ConfigAttribute;
//import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Service;

import cn.sumpu.app.guoguojie.biz.AdminBiz;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;

@Service
public class MyFilterInvocationSecurityMetadataSource implements
		FilterInvocationSecurityMetadataSource {

	private final static Logger logger = LoggerFactory
			.getLogger(MyFilterInvocationSecurityMetadataSource.class);

	private AdminBiz adminBiz;

	private UrlMatcher urlMatcher = new AntUrlPathMatcher();

//	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

	public void setAdminBiz(AdminBiz adminBiz) {
		this.adminBiz = adminBiz;
	}

	public MyFilterInvocationSecurityMetadataSource() {
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		try {
			return adminBiz.loadAllConfigAttribute();
		} catch (AppBusinessException e) {
			return null;
		}
	}

	// 根据URL，找到相关的权限配置。
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		Map<String, Collection<ConfigAttribute>> resourceMap = null;
//		synchronized (MyFilterInvocationSecurityMetadataSource.class) {
			try {
//				if (null == resourceMap) {
					resourceMap = this.adminBiz.loadResourceDefine();
//				}
			} catch (AppBusinessException e) {
				if (logger.isErrorEnabled()) {
					logger.error("Load resource define failure.", e);
				}
			}
//		}

		// object 是一个URL，被用户请求的url
		String url = ((FilterInvocation) object).getRequestUrl();
		int firstQuestionMarkIndex = url.indexOf("?");
		if (firstQuestionMarkIndex != -1) {
			url = url.substring(0, firstQuestionMarkIndex);
		}
		Iterator<String> ite = resourceMap.keySet().iterator();
		while (ite.hasNext()) {
			String resURL = ite.next();
			if (urlMatcher.pathMatchesUrl(url, resURL)) {
				return resourceMap.get(resURL);
			}
		}

//		// 如果根据请求的URL找不到对应的权限配置，则默认返回“ROLE_ADMIN”权限
//		Collection<ConfigAttribute> defaultCa = new
//		ArrayList<ConfigAttribute>();
//		defaultCa.add(new SecurityConfig("ROLE_ADMIN"));
//		return defaultCa;

		return null;
	}

	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}

}
